package com.scs.application.core.mybatis.handlers;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.baomidou.mybatisplus.core.toolkit.Constants;
import com.scs.application.core.entity.DataEntity;
import com.scs.application.core.entity.TreeEntity;
import com.scs.application.core.utils.StringUtils;
import com.scs.application.modules.sys.security.UserPrincipal;
import org.apache.ibatis.binding.MapperMethod;
import org.apache.ibatis.reflection.MetaObject;
import org.apache.shiro.SecurityUtils;

import java.time.LocalDateTime;

public class DataEntityMetaObjectHandler implements MetaObjectHandler {


    private UserPrincipal getUser() {
        UserPrincipal user = null;
        try {
            user = (UserPrincipal) SecurityUtils.getSubject().getPrincipal();
        } catch (Exception e) {

        }
        if (user == null) {
            user = new UserPrincipal();
            user.setCode("anonymous");
        }
        return user;
    }

    @Override
    public void insertFill(MetaObject metaObject) {

        if (!(metaObject.getOriginalObject() instanceof DataEntity)) {
            return;
        }

        DataEntity entity = (DataEntity) metaObject.getOriginalObject();

        entity.setGmtCreate(LocalDateTime.now());
        entity.setGmtModified(LocalDateTime.now());

        UserPrincipal user = getUser();
        if (StringUtils.isBlank(entity.getCreator())) {
            entity.setCreator(user.getCode());
        }
        if (StringUtils.isBlank(entity.getModifier())) {
            entity.setModifier(user.getCode());
        }
    }

    @Override
    public void updateFill(MetaObject metaObject) {
        if (!(metaObject.getOriginalObject() instanceof MapperMethod.ParamMap)) {
            return;
        }

        MapperMethod.ParamMap originalObject = (MapperMethod.ParamMap) metaObject.getOriginalObject();
        if (!originalObject.containsKey(Constants.ENTITY)) {
            return;
        }

        // 获取到的为实体类
        Object param1 = originalObject.containsKey("param1") ? originalObject.get("param1") : originalObject.get(Constants.ENTITY);
        if (!(param1 instanceof DataEntity || param1 instanceof TreeEntity)) {
            return;
        }

        setFieldValByName("gmtModified", LocalDateTime.now(), metaObject);

        UserPrincipal user = getUser();

        setFieldValByName("creator", user.getCode(), metaObject);
        setFieldValByName("modifier", user.getCode(), metaObject);

    }
}
